package com.company.transmqtt.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

@Configuration
public class MqttConfig {

    @Value("${mqtt.source.broker-url}")
    private String sourceBrokerUrl;

    @Value("${mqtt.source.username}")
    private String sourceUsername;

    @Value("${mqtt.source.password}")
    private String sourcePassword;

    @Value("${mqtt.source.client-id}")
    private String sourceClientId;

    @Value("${mqtt.target.broker-url}")
    private String targetBrokerUrl;

    @Value("${mqtt.target.username}")
    private String targetUsername;

    @Value("${mqtt.target.password}")
    private String targetPassword;

    @Value("${mqtt.target.client-id}")
    private String targetClientId;

    // 源MQTT Broker客户端工厂
    @Bean
    public MqttPahoClientFactory sourceMqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{sourceBrokerUrl});
        options.setUserName(sourceUsername);
        options.setPassword(sourcePassword.toCharArray());
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        System.out.println("Source MQTT connecting to: " + sourceBrokerUrl);
        factory.setConnectionOptions(options);
        return factory;
    }

    // 目标MQTT Broker客户端工厂
    @Bean
    public MqttPahoClientFactory targetMqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{targetBrokerUrl});
        options.setUserName(targetUsername);
        options.setPassword(targetPassword.toCharArray());
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        System.out.println("Target MQTT connecting to: " + targetBrokerUrl);
        factory.setConnectionOptions(options);
        return factory;
    }

    // 源客户端ID
    @Bean
    public String sourceClientId() {
        return sourceClientId;
    }

    // 目标客户端ID
    @Bean
    public String targetClientId() {
        return targetClientId;
    }
}